#include "threadPool.h"

void *threadFunc(void *arg){

	//1.创建一个database数据结构
	MYSQL* mysql = NULL;
	printf("threadFunc\n");
	dataBase_t dataBase;
	snprintf(dataBase.host,sizeof(dataBase.host),"localhost");
	snprintf(dataBase.user,sizeof(dataBase.user),"root");
	snprintf(dataBase.passwd,sizeof(dataBase.passwd),"123");
	snprintf(dataBase.db,sizeof(dataBase.db),"deepsleep");
	initDatabase(&mysql,dataBase);
	printf("连接成功！我是工人，请尽情压榨我\n");

	//2.初始化变量
    threadPool_t * pthreadPool = (threadPool_t *)arg;
	int netfd = 0;
	int command = 0;
	// char *token;
	// char *data;
	//char * file_path = "/home/netdisk/a/";


	//3.从共享变量取出数据
	pthread_mutex_lock(&pthreadPool->mutex);
	
	while(pthreadPool->taskQueueLong.queueSize == 0){
		printf("before\n");
	 	pthread_cond_wait(&pthreadPool->condLong, &pthreadPool->mutex);
		printf("after\n");
	}
	netfd = pthreadPool->taskQueueLong.pFront->netfd;
	command = pthreadPool->taskQueueLong.pFront->header.command;  
	char *token = pthreadPool->taskQueueLong.pFront->header.token;
	char *data = pthreadPool->taskQueueLong.pFront->data;    
	deQueue(&pthreadPool->taskQueueLong);             
	pthread_mutex_unlock(&pthreadPool->mutex);
	printf("I am work! I got netfd = %d,command = %d,token = %s,data = %s\n", netfd,command,token,data);

	//4.todo: 根据token判断一下，是否登录了，
	// 是就解析出用户名，在表里定位，并执行下面的上传下载
	// 否就拒绝，提醒对方登录

	//5.实现上传和下载
	switch(command) {
		case CMD_GETS:     // 下载文件
			//接收请求，参数data是要下载的文件名
			//调函数，找到这个文件
			//调发送函数，发送给客户端
			//int ret = downloadHandle(netfd,mysql,file_path);
			break;
		case CMD_PUTS:     // 上传文件
			//接收请求，参数data是要上传的文件名
			//调函数，接收并创建写入这个文件
			//发送给客户端成功或者失败
			//printf(" 要上传的文件名是 %s\n",data);
			// int ret = uploadHandle(netfd, mysql, file_path);
			// char *hash_name;
			// int file_fd = open(file_path);
			// int hashSha256(file_fd,hash_name);
			// rename(file_path,hash_name);

			// sendCommand(netfd,CMD_PUTS,SUCESS,NULL,0);
			break;	
		default:

			break;
	close(netfd);
	}
	return 0;
}

int makeWorker(threadPool_t *pthreadPool){
    for(int i = 0; i < pthreadPool->tidArr.workerNum; ++i){
        pthread_create(&pthreadPool->tidArr.arr[i],NULL,threadFunc,pthreadPool);
    }
    return 0;
}
